﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using EventManager.Model.Entites;
using EventManager.Model.Factory;
using EventManager.Repositories;
using EventManager.ViewModels;

namespace EventManager.Services.Logic
{
    public class EventsServices : IEventsServices
    {
        private IEventsRepository _eventsRepository;
        private ICategoriesRepository _categoriesRepository;
        private IUnitOfWork _unitOfWork;

        public EventsServices(IEventsRepository eventsRepository,
            ICategoriesRepository categoriesRepository, IUnitOfWork unitOfWork)
        {
            _eventsRepository = eventsRepository;
            _categoriesRepository = categoriesRepository;
            _unitOfWork = unitOfWork;
        }

        public ViewModels.EventViewModel GetEventForCreate()
        {
            var categories = _categoriesRepository.GetList()
                .Select(n => new CategoryViewModel
                {
                    Id = n.Id,
                    Name = n.Name
                }).ToList();


            return new EventViewModel
            {
                Id = Guid.NewGuid(),
                StartDate = DateTime.Now,
                EndDate = DateTime.Now,
                Categories = categories,
                SelectedCategories = new List<Guid>()
            };
        }


        public bool ChceckEventNameAvailability(string name)
        {
            bool result = true;
            if (_eventsRepository.GetList().Any(n=>n.Name == name))
            {
                result = false;
            }

            return result;
        }


        public bool SaveEvent(EventViewModel viewModel)
        {
            try
            {
                var e = new Events
                    {
                        Id = viewModel.Id,
                        Name = viewModel.Name,
                        StartDate = viewModel.StartDate,
                        EndDate = viewModel.EndDate,
                        Description = viewModel.Description
                    };

                foreach (var item in viewModel.SelectedCategories)
                {
                    var category = _categoriesRepository.Single(item);
                    e.Categories.Add(category);
                }

                _eventsRepository.Add(e);

                _unitOfWork.Commit();
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
    }
}
